package ui {
	
	import org.flixel.*;
	
	public class SelectionMenu extends FlxGroup
	{
		private var _selections:Array;
		
		private var _currentPosition:int;
		
		private var _escapeCallback:Function;
		private var _sfx:FlxSound;
		
		public function SelectionMenu(maxSize:uint = 6)
		{
			super(maxSize);
			_selections = new Array();
		}
		
		public function addTextOption(t:FlxText, on_color:uint, callback:Function):void
		{
			var on_text:FlxText = new FlxText(t.x, t.y, t.width, t.text);
			on_text.color = on_color;
			on_text.size = t.size;
			on_text.font = t.font;
			on_text.alignment = t.alignment;
			addOption(t, on_text, callback);
		}
		
		public function addOption(off:FlxSprite, on:FlxSprite, callback:Function):void
		{
			on.visible = false;
			off.visible = true;
			add(off);
			add(on);
			_selections.push([off, on, callback]);
			moveSelection(0);
		}
		
		public function set escapeCallback(callback:Function):void
		{
			_escapeCallback = callback;
		}
		
		public function set sfx(s:FlxSound):void
		{
			_sfx = s;
		}
		
		public function moveSelection(dir:int):void
		{
			//switch off old:
			(_selections[_currentPosition][0] as FlxBasic).visible = true;
			(_selections[_currentPosition][1] as FlxBasic).visible = false;
			
			//alter position:
			_currentPosition += dir;
			if (_currentPosition < 0) _currentPosition = _selections.length - 1;
			else if (_currentPosition >= _selections.length) _currentPosition = 0;
			
			//switch on new:
			(_selections[_currentPosition][0] as FlxBasic).visible = false;
			(_selections[_currentPosition][1] as FlxBasic).visible = true;
			
			//play sfx:
			if (_sfx != null) _sfx.play();
		}
		
		override public function update():void
		{
			super.update();
			if (FlxG.keys.justPressed("DOWN"))
			{
				moveSelection(1);
			}
			if (FlxG.keys.justPressed("UP"))
			{
				moveSelection(-1);
			}
			if (FlxG.keys.justPressed("ESCAPE") && _escapeCallback != null)
			{
				_escapeCallback();
			}
			if (FlxG.keys.justPressed("SPACE") || FlxG.keys.justPressed("ENTER"))
			{
				//Selected:
				_selections[_currentPosition][2]();
			}
		}
		
		public function hide():void
		{
			kill();
		}
		
		public function show():void
		{
			for each (var b:FlxBasic in members){
				b.revive();
			}
			revive();
		}
	}
	
}